package com.fingard.dsp.bank.directbank.bocom13.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 用来产生文件的MD5码
 * 
 * @author fanghh
 * @date 2019/4/16
 */
public class MD5 {
	private static final int BUFFER = 8192;
	private static final byte hex[] = "0123456789ABCDEF".getBytes();

	/**
	 * 将16进制字符串转换成字节数组
	 * 
	 * @param hexstr
	 * @return
	 */
	public static byte[] hexStr2Bytes(String hexstr) {
		byte b[] = new byte[hexstr.length() >> 1];
		int j = 0;
		for (int i = 0; i < b.length; i++) {
			char c0 = hexstr.charAt(j++);
			char c1 = hexstr.charAt(j++);
			b[i] = (byte) (parse(c0) << 4 | parse(c1));
		}

		return b;
	}

	private static int parse(char c) {
		if (c >= 'a')
			return (c - 97) + 10 & 0xf;
		if (c >= 'A')
			return (c - 65) + 10 & 0xf;
		else
			return c - 48 & 0xf;
	}

	/**
	 * 将字节数组转换成16进制字符串
	 * 
	 * @param b
	 * @return
	 */
	public static String bytes2HexStr(byte b[]) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < b.length; i++)
			sb.append(byteToHexString(b[i]));
		return sb.toString();
	}

	/**
	 * 将字节转换成16进制字符串
	 * 
	 * @param b
	 * @return
	 */
	private static String byteToHexString(byte b) {
		byte buff[] = new byte[2];
		buff[0] = hex[b >> 4 & 0xf];
		buff[1] = hex[b & 0xf];
		return new String(buff);
	}
	
	public static String generateFileMD5(String filePath) throws Exception {
        int n = 0;
        MessageDigest md = MessageDigest.getInstance("MD5");
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(new File(filePath));
            byte data[] = new byte[BUFFER];
            while ((n = fis.read(data, 0, BUFFER)) != -1)
                md.update(data, 0, n);
            fis.close();
            byte[] md5 = md.digest();
            return bytes2HexStr(md5);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        } finally {
            if (fis != null) {
                fis.close();
            }
        }

	}

	// 产生报文的MD5码,并转换成16进制字符串
	public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
        FileInputStream fis = null;
	    try {
			int n = 0;

			long startTime = System.currentTimeMillis();

			MessageDigest md = MessageDigest.getInstance("MD5");

			fis = new FileInputStream(new File(args[0]));

			byte data[] = new byte[BUFFER];

			while ((n = fis.read(data, 0, BUFFER)) != -1)
				md.update(data, 0, n);

			fis.close();

			byte[] md5 = md.digest();

			System.out.println("[" + bytes2HexStr(md5) + "]");

			long entTime = System.currentTimeMillis();
			System.out.println("系统执行时间是：" + (entTime - startTime) + "毫秒");
		}

		catch (IOException e) {
			e.printStackTrace();
		} finally {
	        if (fis != null) {
	            fis.close();
            }
        }
	}
}
